<script>
import { getProductCarList, delProductCar, modifyTheQuantity } from '@/api/mall.js';

export default {
  name: "list",
  data() {
    return {
      cartList: [], // 购物车商品列表（扁平化后的商品列表）
      businessList: [], // 按商家分组的原始数据
      selectedItems: [], // 选中的商品ID列表
      isEdit: false, // 是否处于编辑状态
      isSelectAll: false, // 是否全选
      loading: false, // 加载状态
      totalPrice: 0, // 总价
      selectedCount: 0, // 选中商品数量
      updatingItems: [] // 正在更新数量的商品ID列表
    }
  },
  onLoad() {
    // 设置导航栏标题
    uni.setNavigationBarTitle({
      title: this.$t('cart.title')
    });
  },
  computed: {
    // 是否有选中商品
    hasSelectedItems() {
      return this.selectedItems.length > 0;
    },
    
    // 计算选中商品的总价
    calculatedTotalPrice() {
      let total = 0;
      this.businessList.forEach(business => {
        if (business.ProductInfo && Array.isArray(business.ProductInfo)) {
          business.ProductInfo.forEach(item => {
            if (this.selectedItems.includes(item.Id)) {
              total += item.Price * item.Num;
            }
          });
        }
      });
      return total;
    }
  },
      watch: {
      selectedItems: {
        handler(newVal) {
          this.selectedCount = newVal.length;
          this.totalPrice = this.calculatedTotalPrice;
          // 更新全选状态 - 计算总商品数量
          const totalProducts = this.getTotalProductCount();
          this.isSelectAll = newVal.length > 0 && newVal.length === totalProducts;
        },
        immediate: true
      },
      businessList: {
        handler() {
          // 当商品列表变化时，清空之前的选中状态
          this.selectedItems = [];
        },
        immediate: true
      }
    },
  methods: {
    // 查询购物车列表
    async queryList(pageNo, pageSize) {
      try {
        const { Data } = await getProductCarList({
          Index: pageNo,
          Size: pageSize
        });
        
        // 处理数据格式 - 新格式是按商家分组的
        const businessList = Array.isArray(Data) ? Data : [];
        
        // 将商家分组的数据扁平化为商品列表
        const flatCartList = [];
        businessList.forEach(business => {
          if (business.ProductInfo && Array.isArray(business.ProductInfo)) {
            business.ProductInfo.forEach(product => {
              // 为每个商品添加商家信息
              flatCartList.push({
                ...product,
                BusinessName: business.BusinessName,
                // 处理商品数据格式
                Count: product.Num || 1,
                ProductName: product.ProductName,
                ProductImg: product.Img,
                ProductSpecStr: this.formatProductSpec(product)
              });
            });
          }
        });
        
        this.$refs.paging.complete(flatCartList);
        this.businessList = businessList;
        this.cartList = this.$refs.paging.completeList;
        
      } catch (error) {
        console.error('获取购物车列表失败:', error);
        this.$refs.paging.complete(false);
        uni.showToast({
          title: '获取购物车列表失败',
          icon: 'none'
        });
      }
    },

    // 切换编辑状态
    toggleEdit() {
      this.isEdit = !this.isEdit;
      if (!this.isEdit) {
        // 退出编辑时清空选中状态
        this.selectedItems = [];
      }
    },

    // 选择/取消选择商品
    toggleSelectItem(itemId) {
      const index = this.selectedItems.indexOf(itemId);
      if (index > -1) {
        this.selectedItems.splice(index, 1);
      } else {
        this.selectedItems.push(itemId);
      }
    },

    // 全选/取消全选
    toggleSelectAll() {
      if (this.isSelectAll) {
        this.selectedItems = [];
      } else {
        // 获取所有商品的ID
        const allProductIds = [];
        this.businessList.forEach(business => {
          if (business.ProductInfo && Array.isArray(business.ProductInfo)) {
            business.ProductInfo.forEach(item => {
              allProductIds.push(item.Id);
            });
          }
        });
        this.selectedItems = allProductIds;
      }
    },

    // 删除选中商品
    async deleteSelected() {
      if (!this.hasSelectedItems) {
        uni.showToast({
          title: this.$t('cart.selectItemsFirst'),
          icon: 'none'
        });
        return;
      }

      uni.showModal({
        title: this.$t('cart.confirmDelete'),
        content: this.$t('cart.deleteSelectedItems', { count: this.selectedItems.length }),
        success: async (res) => {
          if (res.confirm) {
            await this.performDelete();
          }
        }
      });
    },

    // 执行删除操作
    async performDelete() {
      try {
        uni.showLoading({
          title: this.$t('cart.deleting'),
          mask: true
        });

        // 调用删除接口
        await delProductCar({
          ProductCarIdArr: this.selectedItems.join(',')
        });

        uni.hideLoading();
        uni.showToast({
          title: this.$t('cart.deleteSuccess'),
          icon: 'success'
        });

        // 刷新列表
        this.selectedItems = [];
        this.isEdit = false;
        this.$refs.paging.reload();

      } catch (error) {
        uni.hideLoading();
        console.error('删除商品失败:', error);
        uni.showToast({
          title: this.$t('cart.deleteFailed'),
          icon: 'none'
        });
      }
    },

    // 结算
    goToCheckout() {
      if (!this.hasSelectedItems) {
        uni.showToast({
          title: this.$t('cart.selectItemsFirst'),
          icon: 'none'
        });
        return;
      }

      // 获取选中的商品数据
      const selectedProducts = [];
      this.businessList.forEach(business => {
        if (business.ProductInfo && Array.isArray(business.ProductInfo)) {
          business.ProductInfo.forEach(item => {
            if (this.selectedItems.includes(item.Id)) {
              selectedProducts.push({
                ...item,
                BusinessName: business.BusinessName,
                BusinessId: business.BusinessId
              });
            }
          });
        }
      });

      // 跳转到结算页面，传递选中的商品数据
      uni.navigateTo({
        url: `/mall_subpages/cart/predetermined?cartData=${encodeURIComponent(JSON.stringify(selectedProducts))}`
      });
    },

    // 增加商品数量
    async increaseQuantity(item) {
      // 防止重复操作
      if (this.updatingItems.includes(item.Id)) {
        return;
      }
      
      const newQuantity = item.Num + 1;
      await this.updateQuantity(item, newQuantity);
    },

    // 减少商品数量
    async decreaseQuantity(item) {
      // 防止重复操作
      if (this.updatingItems.includes(item.Id)) {
        return;
      }
      
      if (item.Num <= 1) {
        uni.showToast({
          title: this.$t('cart.minQuantityReached') || '商品数量不能少于1',
          icon: 'none'
        });
        return;
      }
      
      const newQuantity = item.Num - 1;
      await this.updateQuantity(item, newQuantity);
    },

    // 更新商品数量
    async updateQuantity(item, newQuantity) {
      // 前端验证：数量不能小于1
      if (newQuantity < 1) {
        uni.showToast({
          title: this.$t('cart.invalidQuantity') || '商品数量不能少于1',
          icon: 'none'
        });
        return;
      }

      // 添加到更新列表，防止重复操作
      this.updatingItems.push(item.Id);

      try {
        // 调用修改数量接口
        await modifyTheQuantity({
          ProductCarId: item.Id,
          Num: newQuantity
        });

        // 更新本地数据
        item.Num = newQuantity;
        
        // 重新计算总价
        this.totalPrice = this.calculatedTotalPrice;

      } catch (error) {
        console.error('更新商品数量失败:', error);
        
        uni.showToast({
          title: error.Msg || this.$t('cart.updateFailed') || '更新失败，请重试',
          icon: 'none'
        });
        
        // 如果更新失败，可以考虑刷新页面数据
        // this.$refs.paging.reload();
      } finally {
        // 从更新列表中移除
        const index = this.updatingItems.indexOf(item.Id);
        if (index > -1) {
          this.updatingItems.splice(index, 1);
        }
      }
    },

    // 跳转到商品详情
    goToProductDetail(item) {
      uni.navigateTo({
        url: `/mall_subpages/goods/index?id=${item.ProductId}&type=${item.BusinessId}`
      });
    },

    // 去购物
    goShopping() {
      uni.switchTab({
        url: '/pages/mall/index'
      });
    },

    // 格式化商品规格信息
    formatProductSpec(product) {
      // 如果有 ProductSpecModel.SpecName，使用它
      if (product.ProductSpecModel && product.ProductSpecModel.SpecName) {
        return product.ProductSpecModel.SpecName;
      }
      
      // 如果有 ProductAttributeName，尝试解析
      if (product.ProductAttributeName) {
        // ProductAttributeName 格式可能是 "99999:0" 之类的，可以根据实际情况处理
        return product.ProductAttributeName;
      }
      
      return '';
    },

    // 计算总商品数量
    getTotalProductCount() {
      let count = 0;
      this.businessList.forEach(business => {
        if (business.ProductInfo && Array.isArray(business.ProductInfo)) {
          count += business.ProductInfo.length;
        }
      });
      return count;
    }
  }
}
</script>

<template>
  <view class="cart-container">
    <!-- 使用z-paging管理分页 -->
    <z-paging 
      ref="paging" 
      v-model="cartList" 
      @query="queryList"
      :refresher-enabled="true"
      :auto="true"
    >
      <!-- 顶部操作栏 -->
      <template #top>
        <view class="header-bar">
          <text class="title">{{$t('cart.title')}}</text>
          <text class="edit-btn" @click="toggleEdit">
            {{ isEdit ? $t('cart.done') : $t('cart.edit') }}
          </text>
        </view>
      </template>

      <!-- 购物车商品列表 - 按商家分组 -->
      <view class="cart-list">
        <view 
          v-for="(business, businessIndex) in businessList" 
          :key="business.BusinessId" 
          class="business-group"
        >
          <!-- 商家信息头部 -->
          <view class="business-header">
            <view class="business-info">
              <text class="business-name">{{ business.BusinessName }}</text>
            </view>
          </view>

          <!-- 该商家的商品列表 -->
          <view 
            v-for="(item, index) in business.ProductInfo" 
            :key="item.Id" 
            class="cart-item"
          >
            <!-- 选择框 -->
            <view 
              class="checkbox"
              @click.stop="toggleSelectItem(item.Id)"
            >
              <view 
                class="checkbox-inner"
                :class="{ 'checked': selectedItems.includes(item.Id) }"
              >
                <text v-if="selectedItems.includes(item.Id)" class="check-icon">✓</text>
              </view>
            </view>

            <!-- 商品图片 -->
            <view class="product-image" @click="goToProductDetail(item)">
              <image 
                :src="item.Img || item.ProductImg" 
                mode="aspectFill"
                class="image"
              ></image>
            </view>

            <!-- 商品信息 -->
            <view class="product-info">
              <view class="product-name" @click="goToProductDetail(item)">{{ item.ProductName }}</view>
              <view class="product-spec" v-if="formatProductSpec(item)">
                {{ formatProductSpec(item) }}
              </view>
              <view class="price-section">
                <text class="price">¥{{ item.Price }}</text>
                <view class="quantity-control">
                  <view 
                    class="quantity-btn minus"
                    :class="{ 'disabled': updatingItems.includes(item.Id) || item.Num <= 1 }"
                    @click.stop="decreaseQuantity(item)"
                  >
                    <text>-</text>
                  </view>
                  <view class="quantity-display" :class="{ 'updating': updatingItems.includes(item.Id) }">
                    <text v-if="!updatingItems.includes(item.Id)">{{ item.Num }}</text>
                    <view v-else class="loading-spinner"></view>
                  </view>
                  <view 
                    class="quantity-btn plus"
                    :class="{ 'disabled': updatingItems.includes(item.Id) }"
                    @click.stop="increaseQuantity(item)"
                  >
                    <text>+</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <template #empty>
        <!-- 空状态 -->
        <view v-if="businessList.length === 0" class="empty-cart">
          <image
              src="/static/empty-cart.png"
              mode="aspectFit"
              class="empty-image"
          ></image>
          <text class="empty-text">{{$t('cart.emptyCart')}}</text>
          <view class="go-shopping-btn" @click="goShopping">
            <text>{{$t('cart.goShopping')}}</text>
          </view>
        </view>
      </template>

      <!-- 底部操作栏 -->
      <template #bottom>
        <view class="bottom-bar" v-if="getTotalProductCount() > 0">
          <view class="bottom-bar-content">
            <view class="left-section">
              <!-- 全选 -->
              <view class="select-all" @click="toggleSelectAll">
                <view 
                  class="checkbox-inner"
                  :class="{ 'checked': isSelectAll }"
                >
                  <text v-if="isSelectAll" class="check-icon">✓</text>
                </view>
                <text class="select-all-text">{{$t('cart.selectAll')}}</text>
              </view>

              <!-- 价格信息 -->
              <view v-if="!isEdit" class="price-info">
                <text class="total-label">{{$t('cart.total')}}</text>
                <text class="total-price">¥{{ totalPrice.toFixed(2) }}</text>
              </view>
            </view>

            <view class="right-section">
              <!-- 编辑状态：删除按钮 -->
              <view 
                v-if="isEdit" 
                class="delete-btn"
                :class="{ 'disabled': !hasSelectedItems }"
                @click="deleteSelected"
              >
                <text>{{$t('cart.delete')}}({{ selectedCount }})</text>
              </view>
              
              <!-- 非编辑状态：结算按钮 -->
              <view 
                v-else 
                class="checkout-btn"
                :class="{ 'disabled': !hasSelectedItems }"
                @click="goToCheckout"
              >
                <text>{{$t('cart.checkout')}}({{ selectedCount }})</text>
              </view>
            </view>
          </view>
        </view>
      </template>
    </z-paging>
  </view>
</template>

<style scoped lang="scss">
.cart-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

// 顶部操作栏
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;

  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }

  .edit-btn {
    font-size: 28rpx;
    color: #498fff;
  }
}

// 购物车列表
.cart-list {
  background-color: #f5f5f5;
}

// 商家分组
.business-group {
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;

  .business-header {
    padding: 20rpx 30rpx;
    background-color: #f8f9fa;
    border-bottom: 1rpx solid #f0f0f0;

    .business-info {
      display: flex;
      align-items: center;

      .business-name {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
      }
    }
  }
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  .checkbox {
    margin-right: 20rpx;
    flex-shrink: 0;
  }

  .checkbox-inner {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    border: 2rpx solid #ddd;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;

    &.checked {
      background-color: #498fff;
      border-color: #498fff;
    }

    .check-icon {
      color: #fff;
      font-size: 24rpx;
      font-weight: bold;
    }
  }

  .product-image {
    width: 160rpx;
    height: 160rpx;
    margin-right: 20rpx;
    border-radius: 8rpx;
    overflow: hidden;

    .image {
      width: 100%;
      height: 100%;
    }
  }

  .product-info {
    flex: 1;
    height: 160rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .product-name {
      font-size: 28rpx;
      color: #333;
      line-height: 1.4;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }

    .product-spec {
      font-size: 24rpx;
      color: #999;
      background-color: #f8f8f8;
      padding: 8rpx 12rpx;
      border-radius: 4rpx;
      margin-top: 10rpx;
      width: fit-content;
    }

    .price-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 10rpx;

      .price {
        font-size: 32rpx;
        color: #ff4757;
        font-weight: bold;
      }

              .quantity-control {
          display: flex;
          align-items: center;

          .quantity-btn {
            width: 50rpx;
            height: 50rpx;
            border-radius: 25rpx;
            border: 1rpx solid #ddd;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #fff;
            transition: all 0.3s ease;

            &.minus {
              color: #999;
              
              &.disabled {
                opacity: 0.3;
                pointer-events: none;
              }
            }

            &.plus {
              background-color: #498fff;
              border-color: #498fff;
              color: #fff;
              
              &.disabled {
                opacity: 0.5;
                pointer-events: none;
              }
            }

            text {
              font-size: 28rpx;
              font-weight: bold;
            }
          }

          .quantity-display {
            margin: 0 20rpx;
            font-size: 28rpx;
            color: #333;
            min-width: 40rpx;
            text-align: center;
            height: 50rpx;
            display: flex;
            align-items: center;
            justify-content: center;

            &.updating {
              opacity: 0.7;
            }

            .loading-spinner {
              width: 20rpx;
              height: 20rpx;
              border: 2rpx solid #f3f3f3;
              border-top: 2rpx solid #498fff;
              border-radius: 50%;
              animation: spin 1s linear infinite;
            }
          }
        }
    }
  }
}

// 空购物车状态
.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 60rpx;

  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 40rpx;
    opacity: 0.6;
  }

  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 40rpx;
  }

  .go-shopping-btn {
    background: linear-gradient(135deg, #498fff 0%, #3a7fe6 100%);
    padding: 20rpx 60rpx;
    border-radius: 30rpx;

    text {
      color: #fff;
      font-size: 28rpx;
    }
  }
}

// 底部操作栏
.bottom-bar {
  background-color: #fff;
  border-top: 1rpx solid #f0f0f0;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));

  .bottom-bar-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left-section {
      display: flex;
      align-items: center;

      .select-all {
        display: flex;
        align-items: center;
        margin-right: 40rpx;

        .select-all-text {
          margin-left: 16rpx;
          font-size: 28rpx;
          color: #333;
        }
      }

      .price-info {
        display: flex;
        align-items: baseline;

        .total-label {
          font-size: 24rpx;
          color: #666;
          margin-right: 10rpx;
        }

        .total-price {
          font-size: 32rpx;
          color: #ff4757;
          font-weight: bold;
        }
      }
    }

    .right-section {
      .delete-btn,
      .checkout-btn {
        padding: 20rpx 40rpx;
        border-radius: 30rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        text {
          font-size: 28rpx;
          color: #fff;
        }

        &.disabled {
          opacity: 0.5;
          pointer-events: none;
        }
      }

      .delete-btn {
        background-color: #ff4757;
      }

      .checkout-btn {
        background: linear-gradient(135deg, #498fff 0%, #3a7fe6 100%);
      }
    }
  }
}

// CSS 动画
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>